import axios from 'axios'
import qs from 'qs'
import { Message } from '@arco-design/web-react'
import cache from '../utils/cache'

// axios实例
const service = axios.create({
  baseURL: process.env.REACT_APP_BASE_URL,
  timeout: 5000,
  headers: { 'Content-Type': 'application/json;charset=UTF-8' },
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    if (cache.getToken()) {
      config.headers.Authorization = 'Bearer ' + cache.getToken()
    }

    // config.headers['Accept-Language'] = cache.getLanguage()

    // 追加时间戳，防止GET请求缓存
    if (config.method?.toUpperCase() === 'GET') {
      config.params = { ...config.params, t: new Date().getTime() }
    }

    if (Object.values(config.headers).includes('application/x-www-form-urlencoded')) {
      config.data = qs.stringify(config.data)
    }

    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      const res = response.data
      // 响应成功
      if (res.code === 0) {
        return res
      }
      // 没有权限，如：未登录、登录过期等，需要跳转到登录页
      if (res.code === 401) {
        cache.setToken('')
        window.location.href = '/login'
        Message.error(res.msg)
        return
      }

      if (res.code === 500) {
        Message.error(res.msg)
        return
      }

      Message.error(res.msg)
    } else {
      Message.error('接口相应异常')
    }
    return

    // 错误提示
    // return Promise.reject(new Error(res.msg || 'Error'))
  },
  (error) => {
    Message.error(error.message)
    // return Promise.reject(error)
  }
)

// 导出 axios 实例
export default service
